/**
 * TabBar
 * @swyan 
 * btnList 按钮列表   type 1文字按钮类型   valX按钮间隔<br>
 * 列表元素<br>
 * 文字按钮类型:{lable:"按钮1",tsize:12,wid:40,hei:30,key:0}<br>
 */
class TabBar extends egret.Sprite {
    /***切换页签***/
    public static ChangeTab: string = "TabBar.ChangeTab";
    
    /**按钮列表*/
    private _btnList: Object[];
    /***按钮类型**/
    private _type: number;
    /***按钮间隔**/
    private _valX: number;

    private _btnSp: egret.Sprite;
    private _btnArr: TabBarBtn[];

    private _curIdx: number;
    private _curBtn: TabBarBtn;
    
    /**
     * btnList 按钮列表   type 1文字按钮类型   valX按钮间隔<br>
     * 列表元素<br>
     * 文字按钮类型:{lable:"按钮1",tsize:12,wid:40,hei:30,key:0}<br>
     */
    public constructor(btnList: Object[],type: number = 1,valX: number = 3) {
        super();
        this._btnList = btnList;
        this._type = type;
        this._valX = valX;

        this.init();
    }

    public addBtns(): void {
        this._btnArr = [];
        this._curIdx = -1;
        this._curBtn = null;
        var btn: TabBarBtn;
        var velX: number = 0;
        for(var i: number = 0;i < this._btnList.length;i++) {
            btn = new TabBarBtn(this._btnList[i],this._type,i);
            btn.x = velX;
            velX += btn.getWid() + this._valX;
            btn.touchEnabled = true;
            btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick,this)
            this._btnSp.addChild(btn);
            this._btnArr.push(btn);
        }
    }

    private onClick(event: egret.TouchEvent): void {
        event.stopPropagation();
        var btn: TabBarBtn = event.currentTarget;

        if(btn && btn.idx != this._curIdx) {
            if(this._curBtn != null)
                this._curBtn.setChoose(false);
            this._curBtn = btn;
            this._curIdx = btn.idx;
            this._curBtn.setChoose(true);
            this.dispatchEvent(new ParamEvent(TabBar.ChangeTab,btn.idx));
        }
    }

    /***设置选中按钮**/
    public setBtnChoose(idx: number): void {
        if(idx > 0 && idx < this._btnArr.length) {
            this._btnArr[idx].dispatchEvent(new egret.TouchEvent(egret.TouchEvent.TOUCH_TAP));
        }
    }

    public removeBtns(): void {
        var btn: TabBarBtn;
        for(var i: number = 0;i < this._btnArr.length;i++) {
            this._btnArr[i].removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick,this);
            this._btnArr[i].dispose();
            this._btnSp.removeChild(this._btnArr[i]);
            this._btnArr[i] = null;
        }
        this._btnArr = [];
    }

    public get curIdx(): number {
        return this._curIdx;
    }

    private init(): void {
        this._btnSp = new egret.Sprite();
        this.addChild(this._btnSp);
    }
}
